<template>
  <div :ref="info._id" v-ui-ref="vSetRef" :class="info._id" class="Virtual-table scorllBox" :style="{ height: tableHeight }">
    <div class="h-table">
      <div
        class="h-thead h-tr absolute top-0 z-10"
        :style="{
          width: trWidth,
        }"
      >
        <div
          v-for="(v, i) of thList"
          :key="i"
          class="p-re"
          :class="{ 'h-td': true, 'left-fixed-a': isFixed == 'left', 'right-fixed-a': isFixed == 'right' }"
          :style="{
            width: v.width,
          }"
        >
          <div v-if="v.key == 'checkbox'" class="flex items-center w-full justify-between bg-cyan-700">
            <!-- tdData.length > 0 ? checkboxAll : false -->
            <van-checkbox v-model="checkboxAll" name="all" @click="ChangeAll(checkboxAll)" />
            <div>{{ v.label }}</div>
          </div>
          <div v-else>
            {{ v.label }}
          </div>
        </div>
      </div>
      <VirtualList v-if="tdData.length > 0" class="VirtualList" :items="tdData" :remain="100" :size="50">
        <template #slotItem="data">
          <div
            class="p-re"
            :class="{
              'h-tr': true,
              'a-color': aIndex == data.data.index ? true : false,
            }"
            :style="{
              width: trWidth,
            }"
            @click="clickTr(data.data)"
          >
            <!-- isShow等于true则表格多选-->

            <div
              v-for="(v, i) in thList"
              :key="i"
              :class="{ 'h-td': true, 'left-fixed-a': isFixed == 'left', 'right-fixed-a': isFixed == 'right' }"
              :style="{
                width: v.width,
              }"
            >
              <div v-if="v.key == 'checkbox'" class="w-full">
                <van-checkbox v-model="data.data.item.checked" :name="data.data.index" @change="checkboxChange(data.data, $event)" />
              </div>

              <div v-if="v.key != 'operate' && v.key != 'checkbox'">{{ data.data.item[v.key] }}</div>
              <!-- 操作按钮 -->
              <div v-if="btns.length > 0 && v.key == 'operate'" :class="btns.length > 1 ? 'operate_btns' : ''">
                <template v-for="(vv, index) in btns" :key="index">
                  <span v-if="data.data.item[`_hidden_${vv._id}`] !== true">
                    {{ vv.extension.name }}
                    <van-button
                      :ref="vv.extension._id"
                      v-ui-ref="vSetRef"
                      :plain="vv.extension.plain.value"
                      :round="vv.extension.round.value"
                      :square="!vv.extension.round.value"
                      style="
                         {
                          width: 100%;
                        }
                      "
                      :type="vv.extension.type.value"
                      @click="operateClick(this, vv, data.data.item)"
                    >
                      <vui-icon v-if="vv.extension.icon.value" :icon="vv.extension.icon.value" />
                      {{ vv.name }}
                    </van-button>
                  </span>
                </template>
              </div>
            </div>
          </div>
        </template>
      </VirtualList>

      <van-empty
        v-else
        class="VirtualList"
        :description="translateTitle('Ve.elements.暂无相关数据')"
        :style="{
          width: trWidth,
        }"
      />
    </div>
    <div v-if="isCheckbox" class="flex justify-end mt-2 text-base">
      已选中
      <span class="text-red-600">{{ allData.length }}</span>
      单
    </div>
  </div>
</template>

<script>
  import { translateTitle } from '@/utils/i18n'
  import VirtualList from './VirtualList'
  import { reactive, toRefs, computed, getCurrentInstance, watch, inject, ref } from 'vue'
  import { UiMixin, RefsInjectMixin } from '@ve/mixin'
  import { Button, Empty, Checkbox, CheckboxGroup } from 'vant'
  import isEmpty from 'lodash/isEmpty'
  import { actionsTask } from '@ve/eventTask/index'
  import { getBody } from '@ve/utils/domHeight'
  import isString from 'lodash/isString'

  export default {
    name: 'UiPdaTable',
    components: {
      VirtualList,
      [Button.name]: Button,
      [Empty.name]: Empty,
      [Checkbox.name]: Checkbox,
      [CheckboxGroup.name]: CheckboxGroup,
    },

    mixins: [UiMixin, RefsInjectMixin],

    emits: ['search', 'click', 'dbclick', 'submit', 'back'],
    setup(props) {
      // 表格高度计算
      const tableHeight = ref('20rem')
      const layoutBoxHeight = inject('layoutBoxHeight')
      const development = inject('development')
      const hasPreview = inject('hasPreview')
      // console.log('tytytytytytytty1', layoutBoxHeight, isString(layoutBoxHeight))
      const setTableHeight = (layoutBoxHeight) => {
        const bodyDom = getBody({ development, hasPreview })
        // 获取兄弟组件的高度
        const tableDom = bodyDom.find(`.${props.info._id}`)
        const siblings = tableDom.parent('.component-box').siblings()
        let domHeight = isString(layoutBoxHeight) ? Number(layoutBoxHeight) : layoutBoxHeight
        // console.log('tytytytytytytty2.5', tableDom.parent())
        // console.log('tytytytytytytty2', layoutBoxHeight, siblings, tableDom.parent('.component-box'), domHeight)
        if (siblings && siblings.length) {
          for (let i = 0; i < siblings.length; i++) {
            domHeight -= siblings[i].clientHeight
          }
        }
        domHeight > 0 && (tableHeight.value = `${domHeight}px`)
      }
      layoutBoxHeight.value && setTableHeight(layoutBoxHeight.value)
      watch(layoutBoxHeight, (newVal) => {
        // console.log('tytytytytytytty3', newVal, isString(newVal))
        if (isString(newVal) || newVal) {
          setTableHeight(newVal)
        }
      })

      let TableDatas = reactive({
        thList: '', //表头
        chacethList: '', //没有"操作"的表头
        tdData: [], //表格数据
        btns: [], //按钮们
        trWidth: '', //总宽度
        isFixed: false, //是否固定操作列
        getOperateMenu: '',
        aIndex: null, //选中的一行
        checkboxAll: false, //全选
        allData: [], //复选数据
        isCheckbox: false,
        outCheckData: [], //外部选中数据缓存
      })
      const { proxy } = getCurrentInstance()
      // 计算处理表格每一行的宽度。宽度百分比超过100%可以左右滚动
      TableDatas.trWidth = computed(() => {
        let width = 0
        for (let obj of TableDatas.thList) {
          width += Number(obj.width.substr(0, obj.width.length - 1))
        }
        return width + '%'
      })
      // 总体处理数据
      function calcDatas() {
        // 判断是否有自定义宽度
        let B = props.info.extension.tableColumns.value.some((v) => {
          console.log('v')
          return v.width != '80' && v.width != 'auto' && v.width != ''
        })
        // 检测自定宽度是否正确
        let ourSelfWidth = 0
        props.info.extension.tableColumns.value.forEach((v) => {
          ourSelfWidth += Number(v.width)
        })
        let arr = []
        // let cahceArr = {}
        let operateMenu = []
        console.log('props.info.extension.operateMenuConfig', props.info.extension.operateMenuConfig)
        if (props.info.extension.operateMenuConfig.value.length > 0) {
          operateMenu = [
            {
              key: 'operate',
              label: translateTitle('Pda.elements.操作'),
              width: 25 + '%',
            },
          ]
          TableDatas.isFixed = props.info.extension.operateMenuConfig.setting.fixed
          TableDatas.btns = props.info.extension.operateMenuConfig.value
        }

        for (let v of props.info.extension.tableColumns.value) {
          if ((B && ourSelfWidth > 100) || ourSelfWidth == 100) {
            // 自定义宽度的时候
            arr.push({
              key: v.field || v._type || v.type,
              label: v.title,
              width: v.width + '%',
            })
          } else {
            // 非自定义宽度   或者自定宽度不对
            arr.push({
              key: v.field || v._type || v.type,
              label: v.title,
              width: 100 / props.info.extension.tableColumns.value.length + '%',
            })
          }
        }
        TableDatas.isCheckbox = computed(() => {
          return props.info.extension.tableColumns.value.some((v) => {
            return v.field == 'checkbox' || v._type == 'checkbox' || v.type == 'checkbox'
          })
        })
        let formData = props.info.data.formData
        console.log('表格数据0:51', formData, props.info)
        delete formData['#LIMIT#']
        delete formData['#PAGE_SIZE#']
        if (!isEmpty(formData)) {
          // 数据注入表格得情况
          TableDatas.tdData = Object.values(formData)
        }
        TableDatas.thList = [...arr, ...operateMenu]
      }

      watch(
        () => props.info.data.formData,
        (newValue) => {
          let formData = newValue
          delete formData['#LIMIT#']
          delete formData['#PAGE_SIZE#']
          if (!isEmpty(formData)) {
            // 数据注入表格得情况
            TableDatas.tdData = Object.values(formData)
          } else {
            TableDatas.tdData = []
          }
        }
      )
      watch(
        () => props.info.extension.tableColumns.value,
        () => {
          calcDatas()
        }
      )

      TableDatas.getOperateMenu = computed(() => props.info.extension.operateMenuConfig.value)
      //按钮操作
      function operateClick(_this, v, data) {
        console.log(_this, v, data, TableDatas.getOperateMenu)
        if (TableDatas.getOperateMenu[0].code.length > 0) {
          TableDatas.getOperateMenu.forEach((r) => {
            if (r._id === v._id) {
              actionsTask(
                _this,
                props.info,
                r.code,
                {
                  tableId: props.info._id,
                  data: [data],
                },
                () => {
                  console.log('操作按钮事件 完成了')
                }
              )
            }
          })
        } else {
          console.log('未配置交互')
        }
      }

      // 点击表格行
      var lastTapDiffTime = ''
      var lastTapTimeoutFunc = ''
      function clickTr(obj) {
        let curTime = new Date().getTime()
        let lastTime = lastTapDiffTime
        lastTapDiffTime = curTime
        //两次点击间隔小于300ms, 认为是双击
        let diff = curTime - lastTime
        //变色
        TableDatas.aIndex = obj.index
        if (diff < 300) {
          proxy.runEventTask('onTableDblClick', {
            tableId: props.info._id,
            data: [obj.item],
          })
          clearTimeout(lastTapTimeoutFunc) // 成功触发双击事件时，取消单击事件的执行
        } else {
          // 单击事件延时300毫秒执行
          lastTapTimeoutFunc = setTimeout(function () {
            proxy.runEventTask('onTableClick', {
              tableId: props.info._id,
              data: [obj.item],
            })
          }, 300)
        }
      }

      //复选
      const checkboxChange = () => {
        TableDatas.allData = TableDatas.tdData.filter((item) => item.checked)
        //如果复选数据长度等于表格数据长度则全选
        if (TableDatas.allData.length == TableDatas.tdData.length) {
          TableDatas.checkboxAll = true
        } else {
          TableDatas.checkboxAll = false
        }

        console.log('tdData', TableDatas.allData)
      }

      //全选
      const ChangeAll = (n) => {
        TableDatas.allData = TableDatas.tdData.filter((item) => item.checked)
        TableDatas.tdData.forEach((item) => {
          if (TableDatas.allData.length) {
            item.checked = n
          } else {
            item.checked = n
          }
        })
      }
      calcDatas()

      return {
        ...toRefs(TableDatas),
        translateTitle,
        operateClick,
        clickTr,
        checkboxChange,
        ChangeAll,
        tableHeight,
      }
    },
  }
</script>

<style lang="scss" scoped>
  .p-re {
    position: relative;
  }
  .uiPdaTable {
    min-height: 100%;
  }
  .Virtual-table {
    height: 20rem;
    width: 100%;
    .van-button--normal {
      height: 1.3rem;
      width: 100%;
      // font-size: 0.2rem;
      padding: 1px 0px;
      color: #7b7a7a;
    }
    .operate_btns .van-button--normal {
      width: auto;
    }
    .van-button__content {
      width: 100%;
      .van-button__text {
        width: 100%;
        display: inline-block;
      }
    }
  }

  .h-table {
    height: 100%;
    border-bottom: 1px solid #cccccc;
    overflow-x: scroll;

    .VirtualList {
      height: 83%;
      // overflow-y: scroll;
      width: 100%;
      :deep() {
        .van-checkbox,
        .van-checkbox__icon {
          width: 100% !important;
        }
        .van-checkbox__icon .van-icon {
          display: inline-block !important;
        }
      }
    }
    :deep() {
      .van-checkbox__icon .van-icon {
        width: 1rem;
        height: 1rem;
      }
    }

    /* 行 */
    .h-tr {
      min-height: 3rem;
      box-sizing: border-box;
      display: flex;
      flex-direction: row;
      justify-content: flex-start;
      align-items: stretch;
      align-content: center;
      border-color: rgb(204, 204, 204);
      border-style: solid;
      border-width: 0;
      border-top-width: 1px;
      border-left-width: 1px;
      color: #333;
    }

    /* 单元格 */
    .h-td {
      color: rgb(204, 204, 204);
      box-sizing: border-box;
      padding: 3px;
      word-break: break-all;
      border-color: rgb(204, 204, 204);
      border-style: solid;
      border-width: 0;
      border-right-width: 1px;
      display: flex;
      flex-direction: row;
      flex-wrap: nowrap;
      justify-content: center;
      align-items: center;
      align-content: center;
      font-size: 0.8rem;
      > div {
        width: 100%;
        text-align: center;
      }
    }

    //
    .right-fixed-a:nth-last-child(1) {
      box-shadow: -2px 0px 5px rgba(0, 0, 0, 0.4);
      background-color: #fff;
      position: sticky;
      right: 0px;
    }
    .left-fixed-a:first-child {
      box-shadow: -2px 0px 5px rgba(0, 0, 0, 0.4);
      background-color: #fff;
      position: sticky;
      left: 0px;
    }

    /* 表头 */
    .h-thead {
      height: 3rem;
      width: 100%;
      background-color: rgb(241, 241, 241) !important;
      font-weight: bold;
      position: sticky;
      top: 0px;
      display: flex;
      justify-content: space-between;
      :deep() {
        .van-checkbox {
          width: 50% !important;
        }
        .van-checkbox__icon {
          width: 100% !important;
          text-align: end !important;
        }
        .van-checkbox__icon .van-icon {
          display: inline-block !important;
        }
      }

      .h-td {
        color: rgb(62, 62, 62);
        font-size: 0.8rem;
      }
      .h-td:nth-last-child(1) {
        background-color: rgb(241, 241, 241);
      }
      .h-td:first-child {
        background-color: rgb(241, 241, 241);
      }
    }
    .a-color {
      background-color: rgb(21, 39, 119) !important;
    }
  }
</style>
